<?php
/**
 * Created by PhpStorm.
 * User: LiYangBo
 * Date: 2016/5/12
 * Time: 9:25
 */

class AliExpress extends MY_Controller{
    function __construct() {
        parent::__construct();
        //加载模型
        /* $roleAry = array('admin','Shaozhuqiang','jay','judy','lyb','prezwang','david','karina','anna','zlj','AlexTM');
         if(!in_array($this->users['account'],$roleAry)){
             js_goto('','你没有权限！','');
            // redirect(blang_url('orders/order'));

             return;
         }*/
        $this->load->model('ae_model');
    }

    /**
     * 获取维保订单
     */
    public function GetAliExpressWarrantyList(){
        $gp=gp();
        //数据分页
        $gp['page']?$gp['page']=$gp['page']:$gp['page']=1;
        $str='?orderId='.$gp['orderId'].'&country='.$gp['country'];
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url('orders/AliExpress/GetAliExpressWarrantyList'.$str);
        $config['total_rows'] = $this->ae_model->CountAliExpressWarranty(trim($gp['orderId']),$gp['country']);
        $config['uri_segment'] = config_item('enable_lang')?5:4;
        $config['per_page'] = 20;
        $this->pagination->initialize($config);
        $data['pageshow']= $this->pagination->create_links();
        //查询销售数据
        $orderList=$this->ae_model->GetAliExpressOrderList($gp['orderId'],$gp['country'],$config['per_page'],($gp['page']-1)*$config['per_page']);
        $data['orderList']=$orderList;
        $data['countryList']=$this->ae_model->selectCustom('mt_repair_site');
        if($orderList[1]==''){
            $data['AliExpressApiInfo']=$this->GetAliExpressOrder($gp['orderId']);
        }
        $this->load->view('defaults/AliExpress_list',$data);
        $this->load->view('defaults/common/footer',$data);
    }

    /**
     * 查看速卖通订单详情
     * @param string $orderId
     */
    public function ViewAliExpressOrderInfo($orderId=''){
        $data['orderInfo']=$this->ae_model->QueryAliExpressOrderInfo($orderId);
        $this->load->view('defaults/AliExpress_inDetail',$data);
        $this->load->view('defaults/common/footer',$data);
    }

    /**
     * 速卖通品牌型号分国家销售统计
     */
    public function GetAliExpressBrandSalesList(){
        $gp=gp();
        $difference=14;//周期（天）
        $Deadline=$this->ae_model->QueryDeadline();//查询订单最大日期
        $dateDifference= floor((($Deadline-1446197107)/(24*3600))+1)%$difference;//计算超出周期天数
        //计算周期天数时间戳最大值
        $frontTimestamp=date('Y-m-d',$Deadline-(($dateDifference)*24*3600));
        $str='?brand='.$gp['brand'].'&model='.$gp['model'].'&country='.$gp['country'];
        $salesList=$this->ae_model->GetAliExpressBrandSalesList($gp['brand'],$gp['model'],$gp['country']);
        foreach($salesList as &$row){
            //统计增长率
            if($row['frontNum']==0){
                $row['rate']=  round(($row['laterNum']*100),2).'%';
            }
            if($row['laterNum']==0){
                $row['rate']= round((-$row['frontNum']*100),2).'%';
            }
            if($row['frontNum']!=0 && $row['laterNum']!=0){
                $row['rate']= round((($row['laterNum']/$row['frontNum']-1)*100),2).'%';
            }
            $row['pcmAdd']=ceil(($row['laterNum']-$row['frontNum'])*0.06);
            $row['cameraAdd']=ceil(($row['laterNum']-$row['frontNum'])*0.02);
        }
        unset($row);
        $data['salesList']=$salesList;
        $data['countryList']=$this->ae_model->selectCustom('mt_repair_site');
        $data['maxTime']=date('Y-m-d',$Deadline);
        $data['frontTime']=$frontTimestamp;
        $data['str']=$str;
        $this->load->view('defaults/AliExpress_salesList',$data);
        $this->load->view('defaults/common/footer',$data);
    }
    /**
     * 获取维保服务生效订单
     * @param int $page
     * @param string $keyword
     */
    public function GetAliExpressWarrantyValidList(){
        $gp=gp();
        //条件判断
        $gp['page']?$gp['page']=$gp['page']:$gp['page']=1;
        $str='?name='.$gp['name'].'&orderId'.$gp['orderId'].'&country='.$gp['country'].'&ctstatus1='.$gp['ctstatus1'];
        //分页查询
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url('orders/AliExpress/GetAliExpressWarrantyValidList'.$str);
        $config['total_rows'] = $this->ae_model->CountAliExpressWarrantyValid(trim($gp['orderId']),trim($gp['name']),$gp['country'],$gp['ctstatus1']);
        $config['uri_segment'] = config_item('enable_lang')?5:4;
        $config['per_page'] = 20;
        $this->pagination->initialize($config);
        $data['pageshow']= $this->pagination->create_links();
        $AeList=$this->ae_model->GetAliExpressValidOrderList(trim($gp['orderId']),trim($gp['name']),$gp['country'],$gp['ctstatus1'],$config['per_page'],($gp['page']-1)*$config['per_page']);
        //重构数组 生成颜色
        foreach($AeList as &$row){
            switch($row['ctstatus']){
                case '0':
                    $color='';
                    $row['statusStr']='未联系';
                    break;
                case '1':
                    $color='#ff9a00';
                    $row['statusStr']='已联系';
                    break;
                case '2':
                    $color='#009900';
                    $row['statusStr']='客人自己解决问题';
                    break;
                case '3':
                    $color='#0000ff';
                    $row['statusStr']='没有接电话';
                    break;
                case '4':
                    $color='#ff0000';
                    $row['statusStr']='电话不是本人';
                    break;
                case '5':
                    $color='#ff33ff';
                    $row['statusStr']='15天质量问题，联系卖家';
                    break;
                default:
                    $color='';
            }
            $row['color']=$color;
        }
        unset($row);
        $data['AeList']=$AeList;
        $data['str']=$str;
        $this->load->view('defaults/WarrantyList',$data);
        $this->load->view('defaults/common/footer',$data);
    }

    /**
     * 获取速卖通无法识别的订单
     * @param string $msg
     */
    public function GetAliExpressUnrecognizedOrderId($msg=''){
        $gp=gp();
        $UnrecognizedList=$this->ae_model->QueryAliExpressUnrecognizedOrder($gp['brandName']);
        $data['UnrecognizedList']=$UnrecognizedList;
        if($msg=='') {
            $data['msg'] = '当前数据总量：' . count($UnrecognizedList);
        }else{
            $data['msg'] = $msg;
        }
        $this->load->view('defaults/AliExpress_unable',$data);
        $this->load->view('defaults/common/footer',$data);
    }

    /**
     * 获取二手机数据
     */
    public function GetAliExpressUsedData(){
        $gp=gp();
        $usedList=$this->ae_model->GetAliExpressUsedData($gp['brand'],$gp['model'],$gp['country']);
        $data['usedList']=$usedList;
        $data['countryList']=$this->ae_model->selectCustom('mt_repair_site');
        $this->load->view('defaults/AliExpress_used',$data);
        $this->load->view('defaults/common/footer',$data);
    }

    /**
     * 获取速卖通品牌型号
     */
    public function GetAliExpressBrandModel(){
        $gp=gp();
        //条件判断
        $gp['page']?$gp['page']=$gp['page']:$gp['page']=1;
        $str='?brand='.$gp['brand'].'&model'.$gp['model'];
        //分页查询
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url('orders/AliExpress/GetAliExpressBrandModel'.$str);
        $config['total_rows'] = $this->ae_model->CountAliExpressBrandModel($gp['brand'],$gp['model']);
        $config['uri_segment'] = config_item('enable_lang')?5:4;
        $config['per_page'] = 20;
        $this->pagination->initialize($config);
        $data['pageShow']= $this->pagination->create_links();

        $brandModelList=$this->ae_model->GetAliExpressBrandModel($gp['brand'],$gp['model'],$config['per_page'],($gp['page']-1)*$config['per_page']);
        $data['brandModelList']=$brandModelList;
        $this->load->view('defaults/AliExpress_brandmodel',$data);
        $this->load->view('defaults/common/footer',$data);
    }
    /**
     * 导出速卖通联系人数据
     * @param $data
     */
    public function ExportAliExpressWarrantyValidData(){
        $gp=gp();
        $fieldData = array(
            'name'=>'name',
            'telephone'=>'telephone',
            'serviceStartTime'=>'serviceStartTime',
            'country'=>'country',
            'statusStr'=>'statusStr',
            'contact'=>'contact',
            'ctime'=>'ctime',
            'follow_up'=>'follow_up',
        );
        $AeList=$this->ae_model->GetAliExpressValidOrderList(trim($gp['orderId']),trim($gp['name']),$gp['country'],$gp['ctstatus1']);
        foreach($AeList as &$row) {
            switch ($row['ctstatus']) {
                case '0':
                    $row['statusStr'] = '未联系';
                    break;
                case '1':
                    $row['statusStr'] = '已联系';
                    break;
                case '2':
                    $row['statusStr'] = '客人自己解决问题';
                    break;
                case '3':
                    $row['statusStr'] = '没有接电话';
                    break;
                case '4':
                    $row['statusStr'] = '电话不是本人';
                    break;
                case '5':
                    $row['statusStr'] = '15天质量问题，联系卖家';
                    break;
                default:
                    $row['statusStr'] = '';
            }
            $row['ctime']=date('Y-m-d H:i:s',$row['ctime']);
        }
        unset($row);
        excel_output('AliExpressWarrantyData',$fieldData,$AeList);
    }

    /**
     * 导出速卖通销售数据
     */
    public function ExportAliExpressSales(){
        $gp=gp();
        $fiedArray=array(
            'brand'=>'品牌',
            'model'=>'型号',
            'country'=>'国家',
            'frontNum'=>'2周前维保量',
            'laterNum'=>'总维保量',
        );
        $salesList=$this->ae_model->GetAliExpressBrandSalesList($gp['brand'],$gp['model'],$gp['country']);
        excel_output('AliExpressMaintenanceData',$fiedArray,$salesList);
    }
    /**
     * 获取速卖通订单详情
     * @param $orderId
     */
    public function GetAliExpressOrder($orderId){
        $str='api.queryWarrantiesByOrderId';
        $arr=array(
            'supplierId'=>'pandawill',
            'orderId'=>$orderId
        );
        $url=getAliExpressSign($str,$arr);
        $dataList=UrlGet($url);
        return $dataList['dataList'][0];
    }
    public function test(){
        $i=$this->MatchingBrandModel('Letv','1s');
        echo $i;
    }

    /**
     * 添加品牌或者型号
     */
    public function AddBrandOrModel(){
        $gp=gp();
        //更新产品标题
        $this->ae_model->UpdateAliExpressOrderData($gp['id'],array('productName'=>$gp['productName']));
        //新增品牌型号
        $this->ae_model->AddBrandModel($gp['brand'],$gp['model']);
        //返回匹配数据
        $num=$this->MatchingBrandModel($gp['brand'],$gp['model']);
        //给出提示
        $msg='添加成功！共'.$num.'条数据被匹配';
        $this->GetAliExpressUnrecognizedOrderId($msg);
    }
    
    /**
     * 匹配品牌型号
     * @param string $brand
     * @param string $model
     */
    public function MatchingBrandModel($brand='',$model=''){
        set_time_limit(0);
        //统计匹配数目
        $i=0;
        //周期（天）
        $difference=14;
        //查询订单最大日期
        $Deadline=$this->ae_model->QueryDeadline();
        //计算超出周期天数
        $dateDifference= floor((($Deadline-1446197107)/(24*3600))+1)%$difference;
        //计算周期天数时间戳最大值
        $frontTimestamp=strtotime(date('Y-m-d 23:59:59',$Deadline-(($dateDifference)*24*3600)));
        //品牌空格分词数组
        $brandArray=explode(' ',strtolower($brand));
        //型号空格分词数组
        $modelArray=explode(' ',strtolower($model));
        $data=$this->ae_model->QueryAliExpressUnrecognizedOrder();
        foreach($data as $row){
            //标题空格分词数组
            $productNameArray=explode(' ',strtolower($row['productName']));
            //取品牌交集
            $brandIntersect=array_intersect($brandArray,$productNameArray);
            //品牌名称空格合词
            $brandName=implode(' ',$brandIntersect);
            //取型号交集
            $modelIntersect=array_intersect($modelArray,$productNameArray);
            //型号名称空格合词
            $modelName=implode(' ',$modelIntersect);
            //判断是否完全匹配上
            if($brandName==strtolower($brand) && $modelName==strtolower($model)){
                $i +=1;
                //解析产品信息
                $productProperties = json_decode($row['productProperties']);
                if ($productProperties) {
                    //进行二手机统计记录
                    $productArray = (get_object_vars($productProperties));
                    if($productArray['Item Condition']=='Used'){
                        $usedId=$this->ae_model->CheckAliExpressUsedThere($brandName,$modelName,$row['country']);
                        if($usedId){
                            $this->ae_model->UpdateAliExpressUsedCount($usedId,$row['productCount']);
                        }else {
                            $usedData = array(
                                'brand' => $brandName,
                                'model' => $modelName,
                                'number' =>$row['productCount'],
                                'country' => $row['country'],
                            );
                            $this->ae_model->AddAliExpressUsedCount($usedData);
                        }
                    }
                }
                //判断对应国家的品牌型号统计记录是否存在
                $brandModelCountryId = $this->ae_model->QueryBrandModelCountryExists($brand, $model,$row['country']);
                if($brandModelCountryId){
                    //对整周期的数据进行前销量累加
                    if ($row['Deadline'] < $frontTimestamp) {
                        $this->ae_model->UpdateBrandSalesData($brandModelCountryId, 'frontNum', $row['productCount']);
                    }
                    $this->ae_model->UpdateBrandSalesData($brandModelCountryId, 'laterNum', $row['productCount']);
                }else {
                    //新增一条统计
                    $addArray = array(
                        'brand' => $brand,
                        'model' => $model,
                        'laterNum' => $row['productCount'],
                        'country' => $row['country']
                    );
                    $BrandSalesId = $this->ae_model->AddBrandSalesData($addArray);
                    //判断是否属于周期前
                    if ($row[''] < $frontTimestamp) {
                        $this->ae_model->UpdateBrandSalesData($BrandSalesId, 'frontNum', $row['productCount']);
                    }
                }
                $this->ae_model->UpdateAliExpressOrderData($row['orderId'], array('is_count' => 1));
            }else{
                if($brandName==$brand){
                    $this->ae_model->UpdateAliExpressOrderData($row['orderId'], array('is_count' => 3,'brandName'=>$brand));
                }
            }
        }
        return $i;
    }

    /**
     * 检查Order
     * @param string $type
     * @param string $fileName
     */
    public function  CheckAeOrder($type='',$fileName=''){
        $data=ExcelToArray("E:/excel/$fileName.xls");
        foreach($data as $row){
            $XEO[]=$row[0];
            $orderId=$this->ae_model->QueryOrderId($row[0]);
            if($orderId==''){
                $just[]['orderId']= $row[0];
            }
        }
        $fieldData = array(
            'orderId'=>'orderId',
        );
        switch($type){
            case 'just':
                excel_output('CheckAeOrder',$fieldData,$just);
                break;
            case 'against':
                $AeData=$this->ae_model->GetAliExpressOrderList();
                foreach($AeData as $val){
                    if(!in_array($val['orderId'],$XEO)){
                        $against[]['orderId']= $val['orderId'];
                    }
                }
                excel_output('CheckAeOrder',$fieldData,$against);
                break;
        }
    }
}